package base.audio;

import java.net.InetAddress;

import base.Util;



public class AudioPacket {
	private int seqNum;
	private long timeStamp;
	private long tempoExecucao;

	private short dataLength;
	private byte[] data;

	private InetAddress senderIp;
	private int senderPort;

	public InetAddress getSenderIp() {
		return senderIp;
	}

	public void setSenderIp(InetAddress senderIp) {
		this.senderIp = senderIp;
	}

	public int getSenderPort() {
		return senderPort;
	}

	public void setSenderPort(int senderPort) {
		this.senderPort = senderPort;
	}
	
	public long getTimestamp(){
		return this.timeStamp;
	}

	public long getTempoExecucao() {
		return tempoExecucao;
	}
	
	public void setTempoExecucao(long tempoExecucao) {
		this.tempoExecucao = tempoExecucao;
	}
	
	public AudioPacket(long timestamp, byte[] data) {
		this.setSeqNum(0);
		this.setData(data);
		this.timeStamp = timestamp;
	}

	public AudioPacket(byte[] pkt) {
		byte[] seq_num = new byte[4];
		byte[] timestamp = new byte[8];
		byte[] data_lenght = new byte[2];

		System.arraycopy(pkt, 0, seq_num, 0, 4);
		System.arraycopy(pkt, 4, timestamp, 0, 8);
		System.arraycopy(pkt, 12, data_lenght, 0, 2);

		this.seqNum = Util.bytesToInt(seq_num);
		this.timeStamp = Util.bytesToLong(timestamp);
		this.dataLength = Util.bytesToShort(data_lenght);

		byte[] data = new byte[this.dataLength];
		if (this.dataLength != 0) {
			System.arraycopy(pkt, 14, data, 0, this.dataLength);
			this.data = data;
		} else {
			this.data = null;
		}
	}

	public int getSeqNum() {
		return seqNum;
	}

	public void setSeqNum(int seqNum) {
		this.seqNum = seqNum;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		if (data != null) {
			this.data = data;
			this.dataLength = (short) data.length;
		} else {
			this.data = null;
			this.dataLength = 0;
		}
	}

	private byte[] getBytes(boolean attach_checksum) {
		byte[] retorno = new byte[14 + this.dataLength];

		byte[] seq_num = Util.intToBytes(this.seqNum);
		byte[] timestamp = Util.longToBytes(this.timeStamp);
		byte[] data_lenght = Util.shortToBytes(this.dataLength);

		System.arraycopy(seq_num, 0, retorno, 0, 4);
		System.arraycopy(timestamp, 0, retorno, 4, 8);		
		System.arraycopy(data_lenght, 0, retorno, 12, 2);
		if (this.data != null)
			System.arraycopy(this.data, 0, retorno, 14, this.dataLength);

		return retorno;
	}

	public byte[] getBytes() {
		return this.getBytes(true);
	}

}
